package com.ysd.shiro;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ysd.common.Result;
import com.ysd.constants.Constants;
import com.ysd.util.JwtUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {


    /**
     * 如果带有 token，则对 token 进行检查，否则直接通过
     */
    @SneakyThrows
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        //判断请求的请求头是否带上 "token"
        if (isLoginAttempt(request, response)) {
            //如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                String msg = e.getMessage();
                Throwable throwable = e.getCause();
                if (throwable != null && throwable instanceof SignatureVerificationException) {
                    msg = "Token或者密钥不正确(" + throwable.getMessage() + ")";
                } else if (throwable != null && throwable instanceof TokenExpiredException) {
                    // AccessToken已过期
                    String token = this.getAuthzHeader(request);
                    if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
                    {
                        token = token.replace(Constants.TOKEN_PREFIX, "");
                    }
                    String username = JwtUtils.getUsername(token);
                    String userId = JwtUtils.getUserId(token);
                    String newToken = JwtUtils.createToken(username, userId);
                    JwtToken jwtToken = new JwtToken(newToken);
                    getSubject(request, response).login(jwtToken);
                    // 设置响应的Header头新Token
                    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                    httpServletResponse.setContentType("application/text;charset=utf8");
                    httpServletResponse.addHeader("newtoken", newToken);
                    httpServletResponse.addHeader("Access-Control-Expose-Headers","newtoken");
                    return true;
                } else {
                    if (throwable != null) {
                        msg = throwable.getMessage();
                    }
                }
                //token 错误
                responseError(response, e.getMessage());
            }
        }
        //如果请求头不存在 token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true
        request.setAttribute("error","用户无token，请登录");
        return false;
    }
    //认证失败
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse hs =  (HttpServletResponse)response;
        hs.setContentType("application/json;charset=utf8");
        ServletOutputStream outputStream = response.getOutputStream();
        String error = (String)request.getAttribute("error");
        outputStream.write(JSONUtil.toJsonStr(Result.fail(402,error,null)).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
        return false;
    }


    /**
     * 判断用户是否想要登入。
     * 检测 header 里面是否包含 token 字段
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        return token != null;
    }

    /**
     * 执行登陆操作
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误它会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /unauthorized/**
     */
    private void responseError(ServletResponse response, String message) throws IOException {
        HttpServletResponse hs =  (HttpServletResponse)response;
        hs.setContentType("application/json;charset=utf8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(Result.fail(402,"用户token错误，请重新登录",null)).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
